import { CurOrgId } from '../../decorators/current-org.decorator';
import { FindOptionsWhere, Repository } from 'typeorm';
import { Timetable } from './models/timetable.entity';
import { Result } from '../../dto/result.type';
import { Args, Mutation, Query, Resolver } from '@nestjs/graphql';
import { UseGuards } from '@nestjs/common';
import { GqlAuthGuard } from '../../guards/auth.guard';
import {
  TimetableResult,
  TimetableResults,
} from './dto/result-timetable.output';
import { TimetableType } from './dto/timetable.type';
import { TimetableService } from './timetable.service';
import { CurUserId } from '../../decorators/current-user.decorator';
import { CourseService } from '../course/course.service';
import { OrderTimeType } from '../course/dto/common.type';
import dayjs from 'dayjs';
import { InjectRepository } from '@nestjs/typeorm';

@Resolver(() => TimetableType)
@UseGuards(GqlAuthGuard)
export class TimetableResolver {
  constructor(
    private readonly timetableService: TimetableService,
    private readonly courseService: CourseService,
    @InjectRepository(Timetable)
    private readonly TimetableRepository: Repository<Timetable>,
  ) {}

  @Query(() => TimetableResult)
  async getTimetableInfo(
    @Args('id') id: string,
  ): Promise<{ data?: Timetable; message: string }> {
    const result = await this.timetableService.findById(id);
    if (result) {
      return {
        data: result,
        message: '获取成功',
      };
    }
    return {
      message: '课程表不存在',
    };
  }

  // 自动创建课程表
  @Mutation(() => Result)
  async autoCreateTimetable(
    @Args('startDay') startDay: string,
    @Args('endDay') endDay: string,
    @CurUserId() userId: string,
    @CurOrgId() orgId: string,
  ): Promise<Result> {
    // 获取当前门店下的所有课程
    const [courses] = await this.courseService.findCourses({
      start: 0,
      length: 100,
      where: {
        orgId,
      },
    });
    const timetables: TimetableType[] = [];
    // 获取每个课程的可约时间
    for (const course of courses) {
      const newReducibleTime: Record<string, OrderTimeType[]> = {};
      const reducibleTime = course.reducibleTime;
      reducibleTime.forEach((item) => {
        newReducibleTime[item.week] = item.orderTime;
      });
      let curDay = dayjs(startDay);
      // 遍历在排课周期中的课
      while (curDay.isBefore(dayjs(endDay).add(1, 'd'))) {
        // 获取当前周几
        const curWeek = curDay.format('dddd').toLocaleLowerCase();
        const orderTime = newReducibleTime[curWeek];
        if (orderTime?.length > 0) {
          for (const time of orderTime) {
            // 判断是否重复创建
            const [allTimetable] = await this.timetableService.findTimetables({
              where: {
                orgId: course.orgId,
                endTime: time.endTime,
                startTime: time.startTime,
                courseId: JSON.stringify({ id: course.id, name: course.name }),
                classDay: curDay.toDate(),
              },
            });
            if (allTimetable.length === 0) {
              const timetable = new Timetable();
              timetable.startTime = time.startTime;
              timetable.endTime = time.endTime;
              timetable.limitNumber = course.limitNumber;
              timetable.orgId = course.orgId;
              timetable.courseId = JSON.stringify({
                id: course.id,
                name: course.name,
              });
              timetable.createdBy = userId;
              timetable.classDay = curDay.toDate();
              const t = await this.TimetableRepository.create(timetable);
              timetables.push(t);
            }
          }
        }
        curDay = curDay.add(1, 'd');
      }
    }
    const res = await this.TimetableRepository.save(timetables);

    return {
      code: !!res,
      message: !!res
        ? `生成课程表成功,共新增${timetables.length}条数据`
        : '生成课程表失败',
    };
  }

  @Query(() => TimetableResults)
  async getTimetables(
    @Args('today') today: string,
    @CurOrgId() orgId: string,
  ): Promise<TimetableResults> {
    const where: FindOptionsWhere<Timetable> = {
      classDay: dayjs(today).toDate(),
      orgId,
    };
    const [results, total] = await this.timetableService.findTimetables({
      where,
    });
    if (results) {
      return {
        data: results,
        page: { total },
        message: '获取成功',
      };
    }
    return {
      message: '获取失败',
    };
  }

  @Mutation(() => Result)
  async deleteTimetable(
    @Args('id') id: string,
    @CurUserId() userId: string,
  ): Promise<Result> {
    const result = await this.timetableService.findById(id);
    if (result) {
      const delRes = await this.timetableService.deleteById(id, userId);
      if (delRes) {
        return {
          message: '删除成功',
        };
      }
      return {
        message: '删除失败',
      };
    }
    return {
      message: '课程表不存在',
    };
  }

  @Query(() => TimetableResults, {
    description: '获取某一个课程近七天的课程表',
  })
  async getTimetablesByCourse(
    @Args('courseId') courseId: string,
  ): Promise<TimetableResults> {
    const [data, total] =
      await this.timetableService.findTimetablesBetweenSevenDay(courseId);
    return {
      data: data,
      message: !!data ? '获取成功' : '获取失败',
      code: true,
      page: {
        total,
      },
    };
  }
}
